<template>
  <div class="p-8 max-w-3xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">随机密码生成器</h1>
    <p class="text-gray-600 mb-6">快速生成符合你需求的高强度密码。可自定义长度和字符集。</p>

    <div class="mb-6">
      <label class="block text-sm font-medium text-gray-700 mb-2">生成的密码</label>
      <div class="flex items-center gap-2">
        <input v-model="password" readonly class="flex-1 px-3 py-2 border rounded bg-gray-50" />
        <button @click="copyToClipboard" class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">复制</button>
        <button @click="generate" class="px-3 py-2 border rounded hover:bg-gray-100">生成</button>
      </div>
      <p v-if="copySuccess" class="text-sm text-green-600 mt-2">已复制到剪贴板</p>
      <p v-if="error" class="text-sm text-red-600 mt-2">{{ error }}</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <div class="col-span-1">
        <label class="block text-sm text-gray-700 mb-1">长度：{{ length }}</label>
        <input type="range" min="4" max="128" v-model.number="length" class="w-full" />
        <input type="number" v-model.number="length" min="4" max="128" class="w-24 mt-2 px-2 py-1 border rounded" />
      </div>

      <div class="col-span-1">
        <label class="block text-sm text-gray-700 mb-1">强度</label>
        <div class="flex items-center gap-2">
          <div class="w-full bg-gray-200 h-3 rounded overflow-hidden">
            <div :style="{ width: strengthPercent + '%' }" :class="strengthColor" class="h-3"></div>
          </div>
          <div class="text-sm w-24 text-right">{{ strengthLabel }}</div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6">
      <label class="inline-flex items-center"><input type="checkbox" v-model="useLower" class="mr-2"> 小写字母 (a-z)</label>
      <label class="inline-flex items-center"><input type="checkbox" v-model="useUpper" class="mr-2"> 大写字母 (A-Z)</label>
      <label class="inline-flex items-center"><input type="checkbox" v-model="useNumbers" class="mr-2"> 数字 (0-9)</label>
      <label class="inline-flex items-center"><input type="checkbox" v-model="useSymbols" class="mr-2"> 符号 (!@#$...)</label>
      <label class="inline-flex items-center col-span-2"><input type="checkbox" v-model="excludeAmbiguous" class="mr-2"> 排除易混淆字符 (0 O 1 l 等)</label>
    </div>

    <div class="flex items-center gap-3">
      <NuxtLink to="/generator-tools" class="text-blue-600 hover:underline">返回生成工具列表</NuxtLink>
      <button @click="generate" class="ml-auto px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">生成密码</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
useHead({ title: '随机密码生成器 - 八八在线工具' })

const password = ref('')
const length = ref(16)
const useLower = ref(true)
const useUpper = ref(true)
const useNumbers = ref(true)
const useSymbols = ref(false)
const excludeAmbiguous = ref(true)
const copySuccess = ref(false)
const error = ref('')

const ambiguousChars = 'O0oIl1'
const lowerChars = 'abcdefghijklmnopqrstuvwxyz'
const upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const numberChars = '0123456789'
const symbolChars = '!@#$%^&*()-_=+[]{};:,.<>/?~'

function buildCharset() {
  let set = ''
  if (useLower.value) set += lowerChars
  if (useUpper.value) set += upperChars
  if (useNumbers.value) set += numberChars
  if (useSymbols.value) set += symbolChars
  if (excludeAmbiguous.value) {
    set = set.split('').filter(c => !ambiguousChars.includes(c)).join('')
  }
  return set
}

function secureRandomInt(max) {
  // Use crypto.getRandomValues when available
  if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
    const arr = new Uint32Array(1)
    crypto.getRandomValues(arr)
    return arr[0] % max
  }
  return Math.floor(Math.random() * max)
}

function generate() {
  error.value = ''
  copySuccess.value = false
  const len = Number(length.value) || 0
  if (len < 4 || len > 128) {
    error.value = '长度应在 4 到 128 之间'
    return
  }
  const charset = buildCharset()
  if (!charset || charset.length === 0) {
    error.value = '请至少选择一种字符集'
    return
  }

  let out = ''
  for (let i = 0; i < len; i++) {
    const idx = secureRandomInt(charset.length)
    out += charset.charAt(idx)
  }
  password.value = out
}

async function copyToClipboard() {
  if (!password.value) return
  try {
    await navigator.clipboard.writeText(password.value)
    copySuccess.value = true
    setTimeout(() => (copySuccess.value = false), 2000)
  } catch (e) {
    // fallback
    const el = document.createElement('textarea')
    el.value = password.value
    document.body.appendChild(el)
    el.select()
    try {
      document.execCommand('copy')
      copySuccess.value = true
      setTimeout(() => (copySuccess.value = false), 2000)
    } finally {
      document.body.removeChild(el)
    }
  }
}

const strengthScore = computed(() => {
  let score = 0
  if (useLower.value) score++
  if (useUpper.value) score++
  if (useNumbers.value) score++
  if (useSymbols.value) score++
  // length contributes up to 4 points
  if (length.value >= 8) score++
  if (length.value >= 12) score++
  if (length.value >= 16) score++
  if (length.value >= 24) score++
  return score // 0..8
})

const strengthPercent = computed(() => Math.min(100, Math.round((strengthScore.value / 8) * 100)))

const strengthLabel = computed(() => {
  const s = strengthScore.value
  if (s <= 2) return '弱'
  if (s <= 4) return '中'
  if (s <= 6) return '强'
  return '非常强'
})

const strengthColor = computed(() => {
  const p = strengthPercent.value
  if (p < 35) return 'bg-red-500'
  if (p < 60) return 'bg-yellow-400'
  return 'bg-green-500'
})

// auto-generate initial password
generate()

// regenerate when key options change for convenience
watch([useLower, useUpper, useNumbers, useSymbols, excludeAmbiguous], () => {
  // only auto-regenerate if there was already a password
  if (password.value) generate()
})
</script>

<style scoped>
</style>
